import { createStore } from 'vuex'
import { ElMessage,ElLoading } from 'element-plus'
import { timestamp, get , post , setCookie , getCookie , delCookie , imgBase , imgCompress,} from '../api/axios'
import router from '../router'
export default createStore({
  state: {
    activeName: 'second',
    // 学员信息
    tableData:[],
    Remarks:'',
    tableDataTwo:[],    // 上传文件前端解析浏览题数据
    tableDataTwoData:[],  // 这才是上传后端的
    question_Data:[],       // 查询全部题目
    examination_show:true,
    userInfor:{
      authority:4,
      name:'',
      phone:'',
      c_id:'',
      className:'',
    },
    TabData:[],
    questionsSize:0,
    generate:{
      subject: [],     // 随机试卷题目拼出来的试卷
    },
    studentData:[],
    Warehousing:[],     // 前端学员分页信息-前端自己做分页
    WarehousingData:[], // 全体学员入库信息保存
    Class_clopedia:[],    // 班级数据
    startData:[],     // 班级考试的数据列表
    startmination:true,   // 开始考试
    historyData:[],
    Question_typename:'',
    gridData:[],
    Analyze_gradesData:[],
  },
  getters: {
  },
  mutations: {
    test_paper(state,subjectData ) {
      state.tableDataTwoData = [];
      state.tableDataTwo = [];
    },
    test_paperTwo(state,subjectData ){
      state.questionsSize = subjectData.page.total
    },
    landingData( state,subjectData ){
      state.userInfor.name = subjectData.u_name
      state.userInfor.authority = subjectData.r_id
      state.userInfor.phone = subjectData.r_name
      sessionStorage.setItem('info',JSON.stringify(subjectData))
      setTimeout(() =>{
        if(state.userInfor.authority == 1){
          router.push({ path: '/Startthe_exam' });
        }else{
          router.push({ path: '/'});
        }
      },1000)
    },
    ClassinformationData(state,subjectData){
      state.Class_clopedia = []
      subjectData.forEach(element => {
        state.Class_clopedia.push({
          value: element.c_id,
          label: element.c_name
        })
      });
      // state.Class_clopedia = []
      // subjectData.forEach(element => {
      //   state.Class_clopedia.push({
      //     value: element.office_id,
      //     label: element.office_name
      //   })
      // });
    },
    Analyze(state,Data){
      state
    }
  },
  actions: {
    // 删除学生
    deleclick({commit,state},value) {
      get('/class/del_stu?uId='+value.u_id+'&cId='+value.valC_id).then(res=>{
        if(res.code == 200){
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
        }
      })
    },
    // 删除试题类型
    deleteqixian({commit,state},value) {
      get('/question/del_by_kind?kind_id='+value).then(res=>{
        
      })
    },
    // 查询考试完的试卷的成绩以及试题
    queryexamin({ commit,state },value){
      get('/history').then(res=>{
        if(res.code == 200){
          state.historyData = res.data
        }else{
          state.historyData = []
        }
      })
    },
    // 查看全部题
    query_subject({ commit,state },value){
      const loading = ElLoading.service({
        lock: true,
        text: '正在获取',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      if(value == undefined){
        value = 1
      }
      get('/question/'+value+'?size=10').then(res=>{
          if(res.code == 200){
            loading.close()
            state.questionsSize = res.page.total
            res.page.records.forEach((item)=>{
              item.answers = item.answers.filter(item => item.a_item != "C.undefined" )
              item.answers = item.answers.filter(item => item.a_item != "D.undefined" )
            })
            state.question_Data = res.page.records
            state.question_Data.forEach((item,index) =>{
              if(item.q_type == 1){
                item.q_type = '多选题'
              }if(item.q_type == 2){
                item.q_type = '判断题'
              }if(item.q_type == 0){
                item.q_type = '单选题'
              }
            })
            commit('test_paper',res)
            ElMessage({
              message: '查询成功',
              type: 'success',
            })
          }
      })
    },
    // 查看所有试题类型
    questionsType({ commit,state }){
      get('/kind/').then(res=>{
        if(res.code == 200){
          state.gridData = res.data
        }else{
          state.gridData = []
        }
      })
    },
    // 上传试卷
    test_paper({ commit,state },Data){
      if(state.tableDataTwoData.length == 0){
        ElMessage({
          message: '请上传题库',
          type: 'error',
        })
        return
      }
      const mapData = JSON.parse( JSON.stringify(state.tableDataTwoData ) )
      const newOptions = mapData.map((item)=>{
        return {
          q_title: item['题干（必填）'],
          q_type: item['题型（必选）'] == "判断题" ? 2:item['题型（必选）'] == "多选题" ? 1:item['题型（必选）'] == "单选题"?0:0,
          answer: item['答案（必填）'],
          q_item: "$"+'A'+item['选项A']+"$"+'B'+item['选项B']+"$"+'C'+item['选项C']+"$"+'D'+item['选项D'],
          kind_id: Data.kind_id,
        }
      })
      let WHQDATA = []
      for(let i=0; i < mapData.length; i++ ){
        WHQDATA.push(newOptions[i])
      }
      const loading = ElLoading.service({
        lock: true,
        text: '正在上传',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      commit('test_paper')
      post('/question/save/batch',JSON.stringify(WHQDATA)).then(res=>{
        if(res.code == 200){
          ElMessage({
            message: '上传成功!',
            type: 'success',
          })
          loading.close()
          router.push('/questions')
        }else{
          ElMessage({
            message: '上传失败!',
            type: 'error',
          })
        }
      })
    },
    Classinformation({ commit },Data){
      get('/class/').then(res=>{
        if(res.code == 200){
          commit('ClassinformationData',res.data)
        }
      })
    },
    // 登陆接口
    landing({ commit },Data){
      post('/login',Data).then(res=>{
        if(res.code == 200) {
          ElMessage({
            message: '登陆成功!',
            type: 'success',
          })
          commit('landingData',res.data)
        }else{
          ElMessage({
            message:'账号密码错误' ,
            type: 'error',
          })
        }
      })
    },
    compound_paper({ commit,state },Data){
      get('/question/each?size='+Data.size+'&type='+Data.type+'&kind_id='+Data.kind_id).then(res=>{
        if(res.code == 200){
          res.data.forEach((item,index) =>{
            item['pwssord'] = []
            item.pwssord.push({
              "a_itemA":'',
              "a_itemB":'',
              "a_itemC":'',
              "a_itemD":'',
            })
          })
          ElMessage({
            message: '获取成功!',
            type: 'success',
          })
          res.data.forEach((item) =>{
            item['answer'] = 0
            if(Array.isArray(item.answers)){
              for(let i=0; i<item.answers.length; i++){
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
              }
            }
          })
          state.generate.subject = res.data
        }
      })
    },
    // 根据班级id查询试卷
    Check_the_paper({ commit,state },Data){
      get('/exam/?c_id='+Data).then(res=>{
        if(res.code == 200){
          state.startData = []
          ElMessage({
            message: '查询成功',
            type: 'success',
          })
          res.data.forEach((item) =>{
            item['answer'] = 0
            item['name'] = item.e_name
            if(Array.isArray(item.answers) ){
              for(let i=0; i<item.answers.length; i++){
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
              }
            }
          })
          res.data.forEach((item) =>{
            item['answer'] = 0
            item['name'] = item.e_name
            if(Array.isArray(item.answers) ){
              for(let i=0; i<item.answers.length; i++){
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
                if(item.answers[i].a_item === "Dundefined" || item.answers[i].a_item === "Cundefined"){
                  item.answers.splice(i,1)
                }
              }
            }
          })
          res.data.forEach((item) =>{
            item['value'] = item.e_id,
            item['label'] = item.e_name
          })
          state.startData = res.data
        }else{
          ElMessage({
            message: '查询失败',
            type: 'error',
          })
        }
      })
    }
  },
})
